package com.yksj.healthtalk.ui.setting;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog.OnClickSureBtnListener;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;


public class SettingEmailBound extends BaseFragmentActivity implements OnClickListener {
	
	private CustomerInfoEntity mCus;
	private Button mNext;
	private PopupWindow mPopUnBund;//是否解除绑定的pop
	private EditText mInputEmaile;
	private boolean SUCCESS_FLAG_EMAIL=false;//true绑定邮箱成功
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.setting_emailbound_layout);
		initView();
	}

	private void initView() {
		initTitle();
		mCus = SmartFoxClient.getLoginUserInfo();
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		titleTextV.setText("绑定邮箱");
		titleLeftBtn.setOnClickListener(this);
		mNext = (Button)findViewById(R.id.next);
		mNext.setOnClickListener(this);
		mInputEmaile = (EditText)findViewById(R.id.setting_input_emaile);
		
		mInputEmaile.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				SystemUtils.hideSoftBord(getApplicationContext(), mInputEmaile);
				comfirm(v);
				return true;
			}
		});
		
		if(mCus.getEmail()!=null&&!mCus.getEmail().trim().equals("")){
			mNext.setText("解除绑定");
			mInputEmaile.setText(mCus.getEmail());
			mInputEmaile.setEnabled(false);
			SUCCESS_FLAG_EMAIL=true;
		}else{
			mNext.setText("绑定");
			SUCCESS_FLAG_EMAIL=false;
			mInputEmaile.setEnabled(true);
//			findViewById(R.id.yanzhengma_layout).setVisibility(View.VISIBLE);
		}
		
	}

	/**
	 * 解除绑定pop
	 */
	private void showMenu(View view){
		if(mPopUnBund==null){
		LayoutInflater mInflater=LayoutInflater.from(this);
		View mPopDeleteView = mInflater.inflate(R.layout.photo_delete_pop,null);
		TextView mTextContent = (TextView)mPopDeleteView.findViewById(R.id.mtext);
		mTextContent.setText("是否解除绑定");
		mPopDeleteView.findViewById(R.id.queren).setOnClickListener(this);
		mPopDeleteView.findViewById(R.id.cancle).setOnClickListener(this);
		mPopUnBund= new PopupWindow(mPopDeleteView,android.view.WindowManager.LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		mPopUnBund.setAnimationStyle(R.style.AnimationPreview);
		mPopUnBund.setBackgroundDrawable(new BitmapDrawable());
		mPopUnBund.setFocusable(true);
		mPopUnBund.showAtLocation(view, Gravity.BOTTOM,0, 0);
		}
		else if(mPopUnBund.isShowing()){
			mPopUnBund.dismiss();return;
		}else{
			mPopUnBund.showAtLocation(view, Gravity.BOTTOM,0, 0);
		}
	}
	
	/**
	 * 绑定邮箱
	 */
	private void comfirm(View v) {
		if (!SystemUtils.isNetWorkValid(this)) {
			ToastUtil.showShort(this, R.string.getway_error_note);
			return;
		}
		if(SUCCESS_FLAG_EMAIL){//解除绑定邮箱
			showMenu(v);
			return ;
		}
		String email = mInputEmaile.getText().toString().trim();
		if (isEmail(email)) {
			HttpRestClient.doHttpSetEmailBound(email, "saveEmailAndCode", SmartFoxClient.getLoginUserId(),new AsyncHttpResponseHandler(this){
				@Override
				public void onSuccess(int statusCode, String value) {
					if (value != null && value.equals("1")){
						SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), getString(R.string.email_bound_success),  new OnClickSureBtnListener() {
							
							@Override
							public void onClickSureHander() {
								SUCCESS_FLAG_EMAIL = true;
								Intent intent = SettingEmailBound.this.getIntent();
								Bundle mBundle=new Bundle();
								if(SUCCESS_FLAG_EMAIL){
									mBundle.putString("email_num", mInputEmaile.getText().toString().trim());
								}
								intent.putExtras(mBundle);
								setResult(RESULT_OK, intent);
								SystemUtils.hideSoftBord(SettingEmailBound.this,mInputEmaile);
								SettingEmailBound.this.finish();
							}
						});
						
					}else {
						SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  getString(R.string.bound_email_fall));
					}
				}
			});
		
		} else {
			SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), getString(R.string.email_toastSpecialcharter));
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.next:
			SystemUtils.hideSoftBord(getApplicationContext(), mInputEmaile);
			comfirm(v);
			break;
		case R.id.queren://确认(解除绑定)
			UnBund();
			break;
		case R.id.cancle://取消
			if(mPopUnBund!=null&&mPopUnBund.isShowing())mPopUnBund.dismiss();
			break;
		}
		
	}

	/**
	 * 解除绑定
	 */
	private void UnBund() {
		if(mPopUnBund!=null&&mPopUnBund.isShowing())mPopUnBund.dismiss();
		//邮箱解除
		HttpRestClient.doHttpUnEmailBind(SmartFoxClient.getLoginUserId(), new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				mInputEmaile.setEnabled(true);
				mInputEmaile.setText("");
				mNext.setText("绑定");
				SUCCESS_FLAG_EMAIL=false;
				SmartFoxClient.getLoginUserInfo().setEmail("");
				ToastUtil.showBasicShortToast(SettingEmailBound.this, "已成功解除绑定");
			}
		});
	
	}
	
	@Override
	public void onBackPressed() {
		Intent intent = this.getIntent();
		Bundle mBundle=new Bundle();
		if(SUCCESS_FLAG_EMAIL){
			mBundle.putString("email_num", mInputEmaile.getText().toString().trim());
		}
		intent.putExtras(mBundle);
		setResult(RESULT_OK, intent);
		SystemUtils.hideSoftBord(this,mInputEmaile);
		finish();
		overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
	}
	
	/**
	 * 邮箱格式判断
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		String strPattern = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(email);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}
	
}
